import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

np.random.seed(0)
n_samples, n_features = 200, 5
X = np.random.randn(n_samples, n_features)
true_coefficients = np.array([4, 2, 0, 0, -1])
y = X.dot(true_coefficients) + np.random.randn(n_samples) * 1.0

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

alpha = 1.0  # 正则化强度参数
ridge = Ridge(alpha=alpha)
ridge.fit(X_train, y_train)

# 输出岭回归模型的系数
print("Ridge Regression Coefficients:", ridge.coef_)

r_squared = ridge.score(X_test, y_test)
print("R-squared:", r_squared)

plt.scatter(y_test, ridge.predict(X_test))
plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Ridge Regression: Actual vs. Predicted")
plt.show()
